package com.song.controller;

import com.song.domain.Material;
import com.song.model.PageResult;
import com.song.service.MaterialService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/materials")
@Validated
public class MaterialController {
    private final MaterialService service;

    public MaterialController(MaterialService service) {
        this.service = service;
    }

    @GetMapping
    public PageResult<Material> list(@RequestParam(defaultValue = "1") int page,
                                     @RequestParam(defaultValue = "10") int size,
                                     @RequestParam(required = false) String category) {
        List<Material> items = service.list(page, size, category);
        int total = service.count(category);
        return new PageResult<>(items, total);
    }

    @GetMapping("/{id}")
    public Material get(@PathVariable Long id) {
        return service.get(id);
    }

    @PostMapping
    public Material create(@Valid @RequestBody Material material) {
        return service.create(material);
    }

    @PutMapping("/{id}")
    public Material update(@PathVariable Long id, @Valid @RequestBody Material material) {
        material.setId(id);
        return service.update(material);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        service.delete(id);
    }
}